<?php
/**
 * REST API - Retrieve all publish announce for a specific user 
 * group
 * 
 */



use Doctrine\DBAL\Connection;
use Hive\Mission\Announce;
use Fox\Dao\SqlFragment;
use Hive\Mission;

$user = User::current();
$groups = $user->groups();
Mission::className();

// Retrieve Params
$xview = Xview::instance();
$aid = $xview->val('aid');
$mid = $xview->val('mid');
$language = $xview->val('language',$xview->language());

if(!empty($mid) || !empty($aid)) {
	$announces = array();
	try {
		$announce = Fox\Dao::load(Announce::className(),$aid.':'.$mid);
		if($announce->status == Announce\Status::PUBLISHED) {
			$mission = $announce->mission();
			if($mission->status != Mission::STATUS_CLOSED) {
				$announces = array($announce);
			}
		}
	} catch(Fox\Object\Exception\NotExist $e) {
		
	}
} else {
	// Load avaible Announces
	$announces = Fox\Dao::finder(Announce::className())
					->where('status = ?',array(Announce\Status::PUBLISHED))
					->follow(Announce::LINK_MISSION)
					->where('loekz = ?',array(0))
					->where('status != ?',array(Mission::STATUS_CLOSED))
					->where('grouping IN (?)',array($groups),array(Connection::PARAM_STR_ARRAY))
					->find();
}
if(is_array($announces) && count($announces) > 0) {
	
	foreach($announces as $announce)
	{
		$data = $announce->getData();
		$data['aid'] = $data['announceid'];
		$data['mid'] = $data['missionid'];
		$alias = Fox\Utilities::cleanup($data['title']);
		$data['alias'] = str_replace(' ','-',$alias);
		$data['contract_type_label']  = null;
		// Job Caracteristics
		if(!empty($data['contract_type'])) {
			$contractType = \Fox\Dao::load(Hive\Job\Contract\Type::className(),$data['contract_type']);
			$data['contract_type_label'] = $contractType->label();
		}
		// Edudcation
		$data['education_level_label']  = null;
		if(!empty($data['education_level'])) {
			$educationLevel = \Fox\Dao::load(Hive\Education\Level::className(),$data['education_level'].':'.$language);
			$data['education_level_label'] = $educationLevel->label;
		}	
		$announcesData[] = $data;
	}
	echo Fox\Utilities::jsonUTF8Encode($announcesData);
} else {
	echo json_encode(array());
}